'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class HomeController extends Controller {
  async login() {
    const { ctx, app } = this;

    // 前端传来的参数
    const { username, password } = ctx.request.body;

    // 在数据库中查找
    const data = await app.mysql.get('userlist', { username, password });

    if (data) {


      ctx.body = {
        code: 1,
        token: jwt.sign(data.id, '1907A'),
      };
    } else {
      // 更改接口状态
      ctx.status = 401;

      ctx.body = {
        code: 0,
        msg: '用户名或者密码错误',
      };
    }
  }

  async userInfo() {
    const { ctx, app } = this;

    // 获取前端传来的token
    const { authorization } = ctx.request.header;

    try {

      // 尝试解密
      const id = jwt.verify(authorization, '1907A');

      // 更具id 从数据库获取用户信息
      const data = await app.mysql.get('userlist', { id });

      ctx.body = {
        code: 1,
        data,
      };

    } catch (error) {
      ctx.status = 403;

      ctx.body = {
        code: 0,
        msg: '登录已过期请重新登录',
      };
    }
  }
}

module.exports = HomeController;
